/**
 * Created by Administrator on 2017/7/18.
 */
let advanceDao = require('../mysql/advanceDao.js');
let mailboxDao = require('../mysql/mailboxDao.js');
let mailDao = require('../mysql/mailDao.js');
let userDao = require('../mysql/userDao.js');
let giftDao = require('../mysql/giftDao.js');
let signInDao = require('../mysql/signInDao.js');
let msg = require('../util/msg.js');
let str = require('../util/str.js');
let variable = require('../data/variable.js');
let gameData = require('../util/gameData.js');

let mail = module.exports;

/**
 * 邮件列表
 * @param userId
 * @param cid
 * @param uuid
 */
mail.list = function (userId, cid, uuid) {
    mail.allList(userId, function (res) {
        msg.send(cid, uuid, 'funcMailList', res);
    });
};
mail.allList = function (userId, cb) {
    mail.boxList(userId, function (res) {
        mail.giftList(userId, function (res1) {
            let list = [];
            if (res) {
                list = list.concat(res);
            }
            if (res1) {
                list = list.concat(res1);
            }
            cb(list);
        });
    });
};
/**
 * 邮箱里的邮件
 * @param userId
 * @param cb
 */
mail.boxList = function (userId, cb) {
    let time = Math.floor(Date.now() / 1000);
    advanceDao.init().table('mailbox')
        .wheres('userId', '=', userId).get(function (err, res) {
        if (err !== null) {
            cb(null);
            return false;
        }
        if (res.length == 0) {
            cb(null);
            return false;
        }
        let ids = [];
        let mailIds = {};
        for (let i in res) {
            ids.push(res[i].mailId);
            mailIds[res[i].mailId] = res[i].id;
        }
        advanceDao.init().table('mail').mails(ids, function (err1, res1) {
            if (err1 !== null) {
                cb(null);
                return false;
            }
            if (res1.length == 0) {
                cb(null);
                return false;
            }
            for (let i in res1) {
                let id = res1[i].id
                res1[i].id = mailIds[id];
                res1[i].time = time - res1[i].time;
            }
            cb(res1);
        });
    });
};
/**
 * 好友送礼模拟邮件
 * @param userId
 * @param cb
 */
mail.giftList = function (userId, cb) {
    let time = Math.floor(Date.now() / 1000);
    advanceDao.init().table('gift').wheres('userId', '=', userId).wheres('take', '=', 0).get(function (err, res) {
        if (err !== null) {
            cb(null);
            return false;
        }
        if (res.length == 0) {
            cb(null);
            return false;
        }
        for (let i in res) {
            res[i].type = 1;
            res[i].source = res[i].name;
            res[i].id = 'G' + res[i].id;
            res[i].time = time - (Date.parse(res[i].date) / 1000);
            res[i].text = '好友送礼';
            res[i].gold = 100;
            res[i].score = 0;
            res[i].gem = 0;
            delete res[i].date;
            delete res[i].name;
        }
        cb(res);
    });
};
/**
 * 单领邮件
 * @param userId
 * @param id
 * @param cid
 * @param uuid
 */
mail.take = function (userId, id, cid, uuid) {
    if (id.substr(0, 1) == 'G') {
        mail.takeGift(userId, id.substr(1), cid, uuid);
    } else {
        mail.takeBox(userId, id, cid, uuid);
    }
};
/**
 * 单领普通邮件
 * @param userId
 * @param id
 * @param cid
 * @param uuid
 */
mail.takeBox = function (userId, id, cid, uuid) {
    let mailboxModel = new mailboxDao();
    mailboxModel.inId(id, function (err, res) {
        if (!res) {
            msg.send(cid, uuid, 'error', {'api': 'funcMailTake', 'code': 10068});
            return false;
        }
        if (userId != res.res.userId) {
            msg.send(cid, uuid, 'error', {'api': 'funcMailTake', 'code': 10069});
            return false;
        }
        let mailModel = new mailDao();
        mailModel.inId(res.res.mailId, function (err1, res1) {
            if (!res1) {
                msg.send(cid, uuid, 'error', {'api': 'funcMailTake', 'code': 10070});
                return false;
            }
            let data = {'gold': res.res.gold, 'score': res.res.score, 'gem': res.res.gem};
            mail.toUser(userId, cid, uuid, data);
        });
        mailboxModel.delete(function () {
        });
    });
};
/**
 * 单领好友送礼
 * @param userId
 * @param id
 * @param cid
 * @param uuid
 */
mail.takeGift = function (userId, id, cid, uuid) {
    let giftModel = new giftDao();
    giftModel.inId(id, function (err, res) {
        if (!res) {
            msg.send(cid, uuid, 'error', {'api': 'funcMailTake', 'code': 10068});
            return false;
        }
        if (userId != res.res.userId) {
            msg.send(cid, uuid, 'error', {'api': 'funcMailTake', 'code': 10069});
            return false;
        }
        if (res.res.take != 0) {
            msg.send(cid, uuid, 'error', {'api': 'funcMailTake', 'code': 10069});
            return false;
        }
        let data = {'gold': 100, 'score': 0, 'gem': 0};
        mail.toUser(userId, cid, uuid, data);
        giftModel.set('take', 1);
        giftModel.save(function () {
        });
    });
};
mail.takeAll = function (userId, cid, uuid) {
    mail.allList(userId, function (list) {
        let giftIds = [], boxIds = [];
        for (let i in list) {
            if (list[i].id.toString().substr(0, 1) == 'G') {
                giftIds.push(list[i].id.toString().substr(1));
            } else {
                boxIds.push(list[i].id);
            }
        }
        let toUser = 0;
        let data = {'gold': 0, 'score': 0, 'gem': 0};
        mail.takeAllBox(boxIds, function (res) {
            toUser++;
            data.gold += res.gold;
            data.score += res.score;
            data.gem += res.gem;
            if (toUser >= 2) {
                mail.toUser(userId, cid, uuid, data);
            }
        });
        mail.takeAllGift(giftIds, function (res) {
            toUser++;
            data.gold += res.gold;
            data.score += res.score;
            data.gem += res.gem;
            if (toUser >= 2) {
                mail.toUser(userId, cid, uuid, data);
            }
        });
    });
};
mail.takeAllBox = function (boxIds, cb) {
    let data = {'gold': 0, 'score': 0, 'gem': 0};
    advanceDao.init().table('mail').mails(boxIds, function (err1, res1) {
        if (err1 !== null) {
            cb(data);
            return false;
        }
        if (res1.length == 0) {
            cb(data);
            return false;
        }
        for (let i in res1) {
            data.gold += res1[i].gold;
            data.score += res1[i].score;
            data.gem += res1[i].gem;
        }
        mail.deleteAllBox(boxIds);
        cb(data);
        return false
    });
};
mail.takeAllGift = function (giftIds, cb) {
    let data = {'gold': 0, 'score': 0, 'gem': 0};
    advanceDao.init().table('gift').mails(giftIds, function (err1, res1) {
        if (err1 !== null) {
            cb(data);
            return false;
        }
        if (res1.length == 0) {
            cb(data);
            return false;
        }
        for (let i in res1) {
            data.gold += 100;
        }
        mail.deleteAllGift(giftIds);
        cb(data);
        return false;
    });
};
mail.deleteAllBox = function (ids) {
    for (let i in ids) {
        advanceDao.init().table('mailbox').wheres('id', '=', ids[i]).delete(function () {

        });
    }
};
mail.deleteAllGift = function (ids) {
    for (let i in ids) {
        advanceDao.init().table('gift').wheres('id', '=', ids[i]).values('take', 1).update(function () {

        });
    }
};
mail.toUser = function (id, cid, uuid, data) {
    if (data.gold + data.score + data.gem <= 0) {
        return false;
    }
    let userModel = new userDao();
    userModel.inId(id, function (err2, res2) {
        if (!res2) {
            msg.send(cid, uuid, 'error', {'api': 'funcMailTake', 'code': 10062});
            return false;
        }
        let resultData = {};
        let save = false;
        let texts = [];
        for (let i in data) {
            if (data[i] <= 0) {
                continue;
            }
            let coin = res2.res[i] + data[i];
            resultData[i] = {'now': coin, 'add': data[i]};
            userModel.set(i, coin);
            save = true;
            texts.push(data[i] + str[i]);
        }
        if (!save) {
            return false;
        }
        userModel.save(function (err3, res3) {
            if (!res3) {
                return false;
            }
            msg.send(cid, uuid, 'globalUserChange', resultData);
            msg.send(cid, uuid, 'globalAlert', {'text': '收到了' + texts.join('，'), 'title': null});
        });
    });
};

/**
 * 好友送礼
 * @param id
 * @param cid
 * @param uuid
 * @param data
 */
mail.giveGift = function (id, cid, uuid, data) {
    let date = new Date().Format("yyyy-MM-dd");
    advanceDao.init().table('gift')
        .wheres('sourceId', '=', id).wheres('date', '=', date)
        .count(function (err, res) {
            //if (err) {
            //    msg.send(cid, uuid, 'globalAlert', {'text': '发送失败', 'title': null});
            //    return false;
            //}
            if (res.res.num >= 30) {
                msg.send(cid, uuid, 'error', {'api': 'funcGiveGift', 'code': 10071});
                return false;
            }

            let giftModel = new giftDao();
            giftModel.inTargetToday(id, data.id, date, function (err1, res1) {
                //if (err1) {
                //    msg.send(cid, uuid, 'globalAlert', {'text': '发送失败', 'title': null});
                //    return false;
                //}
                if (res1) {
                    msg.send(cid, uuid, 'funcGiveGift', {'id': data.id, 'state': 2});
                    return false;
                }
                giftModel.set('userId', data.id);
                giftModel.set('sourceId', id);
                giftModel.set('name', data.name);
                giftModel.set('avatar', data.avatar);
                giftModel.set('date', date);
                giftModel.save(function (err2, res2) {
                    if (err2 != null) {
                        return false;
                    }
                    msg.send(cid, uuid, 'funcGiveGift', {'id': data.id, 'state': 1});
                });
            });
        });
};

mail.dailySignIn = function (userId, cid, uuid) {
    let signInModel = new signInDao();
    signInModel.inId(userId, function (err, res) {
        if (!res) {
            return false;
        }
        let date = new Date().Format("yyyy-MM-dd");
        let dateN = new Date(res.res.date).Format("yyyy-MM-dd");
        if (date == dateN) {
            msg.send(cid, uuid, 'error', {'api': 'funcDailySignIn', 'code': 10072});
            return false;
        }
        let coinAmount = gameData.d.signIn[res.res.times].coin;
        let coinType = gameData.d.signIn[res.res.times].type;
        let times = res.res.times + 1;
        if (times >= gameData.d.signIn.length) {
            times = 0;
        }
        signInModel.set('times', times);
        signInModel.set('date', date);
        signInModel.save(function () {
        });
        let userModel = new userDao();
        userModel.inId(userId, function (err2, res2) {
            if (!res2) {
                msg.send(cid, uuid, 'error', {'api': 'funcDailySignIn', 'code': 10062});
                return false;
            }
            let resultData = {};
            let coin = res2.res[coinType] + coinAmount;
            resultData[coin] = {'now': coin, 'add': coinAmount};
            userModel.set(coinType, coin);
            userModel.save(function (err3, res3) {
                if (!res3) {
                    return false;
                }
                msg.send(cid, uuid, 'globalUserChange', resultData);
                msg.send(cid, uuid, 'globalAlert', {'text': '签到领取了' + coinAmount + '金币', 'title': null});
            });
        });
    });
};